<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class News extends CI_Controller {
	var $perpage = 20;

		public function __construct() {
		   parent::__construct();
		   if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) redirect('auth/login/'.str_replace("/", ".",$_SERVER['REQUEST_URI']));
		   $this->layout->setlayout('admin/layout');
		   $this->crumps->push('/admin/news/', 'Новости');
		   $this->users_rights_model->check_rights(strtolower(get_class()), $this->router->get_method());
	   }

	public function index()	{

		$data['from'] = $from = $this->input->get('from', true);
		if ($from == "") $from = 0;
		$data['pages'] = $pages = $this->db->select()->where_not_in('news_parent',2)->from('news')->limit($this->perpage, $from)->get()->result_array();

		/* pagination */
		$count = $this->db->select()->from('news')->count_all_results();
		if ($from != 0 && sizeof($pages) <= 0 && $count > 0) {
			$pgng = $from - $this->perpage;
			redirect('admin/news/index/?from='.$pgng);
		}
		$this->load->library('pagination');
		$config['base_url'] = '/admin/news/index/';
		$config['total_rows'] = $count;
		$config['page_query_string'] = TRUE;
		$config['per_page'] = $this->perpage;
		$this->pagination->initialize($config);
		$data['paging'] = $this->pagination->create_links();
		/* pagination */

		$this->layout->view('admin/news/index', $data);
	}
	public function edit($id = 0) {
		$this->crumps->push('/admin/news/'.($id == 0?'add':'edit/'.$id).'/', ($id == 0?"Добавление":"Редактирование"));
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('news')->where('news_id', $id)->get()->row_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/news');

		if ($id != 0) $page['news_date'] = date("d.m.Y", $page['news_date']);

		$form = new jQuickForm('simple');


		$random = md5(time()).md5(md5(time()));

		$form->addElement('hidden', 'random')->setValue($random);
		$form->setLabel(($id == 0?"Добавление":"Редактирование").' новости');

		$form->insertInputText('news_title')->setLabel('Название')->addRuleRequired();

		$gr = $form->insertGroup()->addClass('col col2');
		$date = $gr->insertInputText('news_date')->setLabel('Дата новости')->addClass('datepicker');
		if ($id == 0) $date->setValue(date("d.m.Y"));

		$select = $gr->insertSelect('news_parent')->setLabel('Раздел');
		$parents[1] = 'Главные новости';
		$parents[3] = 'Акции';
		$parents[4] = 'Скидки';
		//$parents[2] = 'Блоги';
		foreach ($parents as $key => $val) {
			$select->addOption($val, $key);
		}

		$select = $form->insertSelect('news_pg')->setLabel('Фотогалерея для этой новости')->setComment('<a href="#" class="ajax add_pg">Добавить</a> или <a href="#" class="ajax edit_pg">редактировать эту</a> фотогалерею или <a href="/admin/pg/" target="_blank" class="ajax">посмотреть все</a>');
		$select->addOption('Не выбрана', 0);
		$pgs = $this->db->select()->from('pg')->where('pg_parent', '2')->order_by('pg_id', 'desc')->get()->result_array();
		foreach ($pgs as $pg) {
			$select->addOption($pg['pg_title'], $pg['pg_id']);
		}


		if ($id != 0 && $page['news_image'] != "") {
			$file = $page['news_image'];
			$im = getimagesize('./uploads/news/'.$id.'/small/'.$file);
			$padding = round((150 - $im[1]) / 2);
			$text = "<div class=\"multi_upload_preview\"><img style='margin: ".$padding."px 0 0 0;' src='/uploads/news/".$id."/small/".$file."' alt='Новое изображение' title='Новое изображение' /><a href='#' class='deleteimage' rel=\"one:uploads:news:".$id.":".$file."\"><img src='/data/images/icons/delete.png' alt='Удалить' title='Удалить' /></a></div>";
		}

		$form->insertStatic("<div class='loaded_images' id='loaded_images_news_image_0'>".$text."<br class='cc' /></div>");

		$post_params = array(
			'width' => '200',
			'height' => '200',
			'random' => $random,
			'session' => $this->session->userdata('session_id')
		);
		$form->insertMultiUpload('news_image', '/admin/tools/upload/news/', $post_params, 1, false, 2048000)->setId('news_image_0')->setLabel('Фотография для новости')->setComment('Максимум только одна фотография (jpg/png/gif, 1024Kb, 1000*1000px)');

		$gr = $form->insertGroup()->addClass('col col2');
		$gr->insertInputCheckbox('news_rss', '1')->setLabel('Экспортировать в RSS');
		$gr->insertInputCheckbox('news_bullet', '1')->setLabel('Отображать в правой колонке')->setComment('Если ни одна новость не будет отмечена на отображение - будут показаны 3 последних новости.');

		$form->insertFCKeditor('news_desc')->setLabel('Анонс новости');
		$form->insertFCKeditor('news_text')->setLabel('Текст новости');

		if ($_SERVER['REQUEST_METHOD'] == "POST" && $form->validate()) {
			if ($id == 0) {
				$p_data = $this->input->post();

				$p_data['news_date'] = strtotime($p_data['news_date']);
				$p_data['news_modify'] = time();

				if(!$p_data['news_bullet'])$p_data['news_bullet'] = 0;
				$rand = $p_data['random'];
				unset($p_data['random']);

				$this->db->insert('news', $p_data);
				$result = $this->db->insert_id();

				$files = $this->tools_model->copyfiles($rand, $result, 'news');
				if (sizeof($files) > 0) $this->db->update('news', array('news_image' => $files[0]), array('news_id' => $result));

				$this->session->set_flashdata('msg', 'Успешно добавлено');
				redirect('admin/news/edit/'.$result.'/');
			} else {
				$p_data = $this->input->post();

				$p_data['news_date'] = strtotime($p_data['news_date']);
				$p_data['news_modify'] = time();
				$rand = $p_data['random'];
				unset($p_data['random']);
				if(!$p_data['news_bullet'])$p_data['news_bullet'] = 0;

				$files = $this->tools_model->copyfiles($rand, $id, 'news');
				if (sizeof($files) > 0) $p_data['news_image'] = $files[0]; else unset($p_data['news_image']);

				$this->db->where('news_id', $id)->update('news', $p_data);
				$this->session->set_flashdata('msg', 'Успешно обновлено');
				redirect('admin/news/edit/'.$id.'/');
			}
		}
		$form->insertInputSubmit(($id == 0?"Добавить":"Сохранить"));

		$form->addDataSource(new HTML_QuickForm2_DataSource_Array($page));
		$data['form'] = $form."";
		$data['js'] = jQuickForm::js()->getJsAll();
		$this->layout->view('admin/news/edit', $data);
	}
	public function delete($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('news')->where('news_id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/news');
		$this->db->where('news_id', $id)->delete('news');
		$this->session->set_flashdata('msg', 'Успешно удалено');
		redirect('admin/news/'.$pgng);
	}
	public function block($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('news')->where('news_id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/news');
		$this->db->where('news_id', $id)->update('news', array('news_status' => 0));
		$this->session->set_flashdata('msg', 'Успешно');
		redirect('admin/news/'.$pgng);
	}
	public function unblock($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('news')->where('news_id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/news');
		$this->db->where('news_id', $id)->update('news', array('news_status' => 1));
		$this->session->set_flashdata('msg', 'Успешно');
		redirect('admin/news/'.$pgng);
	}
	public function add() {
		return $this->edit(0);
	}
}